package com.duochuang.verifycard.web;

import com.alibaba.fastjson.JSONObject;
import com.duochuang.verifycard.application.VerifyCardService;
import com.duochuang.verifycard.domain.LockOrder;
import com.duochuang.verifycard.domain.SystemCode;
import com.duochuang.verifycard.domain.SystemCodeRepository;
import com.duochuang.verifycard.exception.InterfaceException;
import com.duochuang.verifycard.util.ConstantUtil;
import com.duochuang.verifycard.util.PetroChinaVerifyCardUtil;
import com.duochuang.verifycard.util.SinopecVerifyCardUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

import static com.duochuang.verifycard.util.ConstantUtil.USER_ID;

/**
 * @author HuLiwen
 * @date 2019-05-18 14:31
 */
@Controller
@Api(value = "加油卡状态查询 OilCardController")
@Slf4j
@CrossOrigin
public class OilCardController {

    @Autowired
    private VerifyCardService verifyCardService;
    @Autowired
    private SystemCodeRepository systemCodeRepository;

    @PostMapping("/queryOilCardStatus")
    @ApiOperation(value = "查询油卡状态",notes = "查询油卡状态")
    @ResponseBody
    public ResponseEntity queryOilCardStatus(@Valid @RequestBody QueryOilCardDTO queryOilCardDTO, BindingResult error){
        if (error.hasErrors()){
            return new ResponseEntity(error.getFieldError().getDefaultMessage(), HttpStatus.NOT_FOUND);
        }
        String result="";
        switch (queryOilCardDTO.getType()){
            case "001": // 中石化
//                cookie = "ticket=\"SSO-550_5TSKYUEPKKROZF5TUO9WY8O8H_H2NW0FSRFQII9FCPJIPMVPRZLIR9W1GVMY0O,687474703A2F2F31302E352E3138302E35353A383038302F77656273736F\"";
                systemCodeRepository.save(new SystemCode(ConstantUtil.SINOPEC_CODE, queryOilCardDTO.getCookie(),
                        "中石化系统cookie"));
                result = SinopecVerifyCardUtil.verifyCard(queryOilCardDTO.getCardNo(), queryOilCardDTO.getCookie()).getMsg();
                break;
            case "002": // 中石油
                systemCodeRepository.save(new SystemCode(ConstantUtil.PETRO_CHINA_CODE, queryOilCardDTO.getCookie(),
                        "中石油系统cookie"));
                result = PetroChinaVerifyCardUtil.verifyCardRetMsg(queryOilCardDTO.getCardNo(), queryOilCardDTO.getCookie());
                break;
        }
        // 返回结果
        return ResponseEntity.status(HttpStatus.OK).body(result);
    }

    @GetMapping("/")
    public String index(){
        return "index";
    }

    @PostMapping("/postCardVerify")
    @ResponseBody
    public ResponseEntity postVerifyCard(@Valid CardVerifyDTO cardVerifyDTO, BindingResult result){

        log.info("用户请求字符串&&&&&&" + "json对象串" + JSONObject.toJSONString(cardVerifyDTO));
        final InterfaceException interfaceRechargeException = new InterfaceException();
        try {
            checkRequestData(result);
            verifyCardService.verifyCard(cardVerifyDTO);
        } catch (InterfaceException e) {
            return new ResponseEntity(e,HttpStatus.CREATED);
        }
        interfaceRechargeException.setStatus(0);
        interfaceRechargeException.setMsg("提交成功");
        return new ResponseEntity(interfaceRechargeException,HttpStatus.CREATED);
    }

    /**
     * 更新cookie, 获取锁定订单
     * @param type
     * @param cookie
     * @return
     */
    @ApiOperation(value = "更新cookie")
    @PutMapping("/code")
    @ResponseBody
    public ResponseEntity modifyCookie(@RequestParam String type,@RequestParam String cookie){
        // 运营商：001-中石化；002-中石油
        switch (type){
            case "001":
                SystemCode systemCode = systemCodeRepository.findById(ConstantUtil.SINOPEC_CODE).get();
                Date updateTime = systemCode.getUpdateTime();
                if (System.currentTimeMillis() - updateTime.getTime() < 1000*60*10){
                    return ResponseEntity.ok("请勿重复修改");
                }
                systemCode.setValue(cookie);
                systemCode.setStatus(true);
                systemCodeRepository.save(systemCode);
                new Thread(()-> verifyCardService.work()).start();
                break;
            case "002":
                systemCode = systemCodeRepository.findById(ConstantUtil.PETRO_CHINA_CODE).get();
                systemCode.setValue(cookie);
                systemCode.setStatus(true);
                systemCodeRepository.save(systemCode);
                break;
        }
        return ResponseEntity.ok("更新成功");
    }

    /**
     * 订单回调
     * @param orderId
     * @param status
     * @param errorCode
     * @param errorMsg
     * @return
     */
    @ApiOperation(value = "订单回调")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orderId", value = "订单号", required=true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name="status", value = "状态 0：失败  1： 成功 2：存疑", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name="errorCode", value = "错误码",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name="errorMsg", value = "错误消息",  dataType = "String", paramType = "query"),
    })
    @GetMapping("/callbackTest")
    public ResponseEntity orderCallback(
            @RequestParam String orderId, @RequestParam String status, String errorCode,String errorMsg){
        VerifyResultDTO verifyResultDTO = new VerifyResultDTO(USER_ID, orderId, status, errorCode, errorMsg);
        verifyCardService.orderCallback(verifyResultDTO);
        return ResponseEntity.ok("操作成功");
    }
    @GetMapping("/callback/{id}")
    public ResponseEntity orderCallback(@PathVariable(value = "id")  LockOrder lockOrder){
        try {
            verifyCardService.orderCallbackById(lockOrder);
        } catch (Exception e){
            return ResponseEntity.ok("操作失败：" + e.getMessage());
        }
        return ResponseEntity.ok("操作成功");
    }

    /**
     * 分页查询锁定订单信息
     * @param orderId
     * @param uId
     * @param callbackStatus
     * @param pageable
     * @return
     */
    @ApiOperation(value = "分页查询锁定订单信息", notes = "分页查询锁定订单信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "条数", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序", dataType = "int", paramType = "query")
    })
    @GetMapping("/order")
    public ResponseEntity<Page<LockOrder>> findAll(
            String orderId, String uId, Boolean callbackStatus,
            @PageableDefault(direction = Sort.Direction.DESC, sort = "createTime") Pageable pageable){
        return ResponseEntity.ok(verifyCardService.findAll(orderId, uId, callbackStatus, pageable));
    }

    /**
     * 检查请求数据
     * @param result
     * @throws InterfaceException
     */
    private void checkRequestData(BindingResult result) throws InterfaceException{

        final InterfaceException interfaceRechargeException = new InterfaceException();

        if(result.hasErrors()){
            List<ObjectError> errorList = result.getAllErrors();
            StringBuffer msg =new StringBuffer();
            for (ObjectError error : errorList) {
                msg.append(error.getDefaultMessage());
                interfaceRechargeException.setStatus(20);
                interfaceRechargeException.setMsg(msg.toString());
            }
            throw  interfaceRechargeException;
        }

    }

}